import { addRule, removeRule, rule, updateRule } from '@/services/ant-design-pro/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
    FooterToolbar,
    ModalForm,
    PageContainer,
    ProDescriptions,
    ProFormText,
    ProFormTextArea,
    ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Input, message } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
// import type { FormValueType } from './components/UpdateForm';
// import UpdateForm from './components/UpdateForm';
import AddPort from '@/components/AddPort';
/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */

const handleAdd = async (fields: API.RuleListItem) => {
    const hide = message.loading('正在添加');
    try {
        await addRule({ ...fields });
        hide();
        message.success('Added successfully');
        return true;
    } catch (error) {
        hide();
        message.error('Adding failed, please try again!');
        return false;
    }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
const handleUpdate = async (fields: FormValueType) => {
    const hide = message.loading('Configuring');
    try {
        await updateRule({
            name: fields.name,
            desc: fields.desc,
            key: fields.key,
        });
        hide();

        message.success('Configuration is successful');
        return true;
    } catch (error) {
        hide();
        message.error('Configuration failed, please try again!');
        return false;
    }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.RuleListItem[]) => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;
    try {
        await removeRule({
            key: selectedRows.map((row) => row.key),
        });
        hide();
        message.success('Deleted successfully and will refresh soon');
        return true;
    } catch (error) {
        hide();
        message.error('Delete failed, please try again');
        return false;
    }
};

const TableList: React.FC = () => {
    /**
     * @en-US Pop-up window of new window
     * @zh-CN 新建窗口的弹窗
     *  */
    const [createModalOpen, handleModalOpen] = useState<boolean>(false);
    /**
     * @en-US The pop-up window of the distribution update window
     * @zh-CN 分布更新窗口的弹窗
     * */
    const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

    const [showDetail, setShowDetail] = useState<boolean>(false);

    const actionRef = useRef<ActionType>();
    const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
    const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);

    const [openAddPort, setOpenAddPort] = useState<boolean>(false);
    /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
    const intl = useIntl();
    //分页
    const queryParams = {
        pageIndex: 1,  //定义当前页
        pageSize: 10   //定义每页的条数
    };
    useEffect(() => {
        queryParams.pageIndex = 1;
        queryParams.pageSize = 10;
    }, [])
    const [gridData, setGridData] = useState<Array<{ id: number, name: string }>>([]);
    const paginationChange = function (page: number, pageSize?: number) {
        queryParams.pageIndex = page;
        queryParams.pageSize = pageSize as number;
        // getgridData()
        let obj = ['', '', '']
        setGridData(obj)
    }
    // 每列具体
    const columns: ProColumns<API.RuleListItem>[] = [
        {
            title: '端口名称',
            dataIndex: 'name',
            tip: '点击可查看端口详情',
            render: (dom, entity) => {
                return (
                    <a
                        onClick={() => {
                            setCurrentRow(entity);
                            setShowDetail(true);
                        }}
                    >
                        {dom}
                    </a>
                );
            },
        },
        {
            title: '能源系统类型',
            dataIndex: 'desc',
            valueType: 'textarea',
        },
        // {
        //     title: (
        //         <FormattedMessage
        //             id="pages.searchTable.titleCallNo"
        //             defaultMessage="Number of service calls"
        //         />
        //     ),
        //     dataIndex: 'callNo',
        //     sorter: true,
        //     hideInForm: true,
        //     renderText: (val: string) =>
        //         `${val}${intl.formatMessage({
        //             id: 'pages.searchTable.tenThousand',
        //             defaultMessage: ' 万 ',
        //         })}`,
        // },
        {
            title: <FormattedMessage id="pages.searchTable.titleStatus" defaultMessage="Status" />,
            dataIndex: 'status',
            hideInForm: true,
            valueEnum: {
                0: {
                    text: (
                        <FormattedMessage
                            id="pages.searchTable.nameStatus.default"
                            defaultMessage="Shut down"
                        />
                    ),
                    status: 'Default',
                },
                1: {
                    text: (
                        <FormattedMessage id="pages.searchTable.nameStatus.running" defaultMessage="Running" />
                    ),
                    status: 'Processing',
                },
                2: {
                    text: (
                        <FormattedMessage id="pages.searchTable.nameStatus.online" defaultMessage="Online" />
                    ),
                    status: 'Success',
                },
                3: {
                    text: (
                        <FormattedMessage
                            id="pages.searchTable.nameStatus.abnormal"
                            defaultMessage="Abnormal"
                        />
                    ),
                    status: 'Error',
                },
            },
        },
        // {
        //     title: (
        //         <FormattedMessage
        //             id="pages.searchTable.titleUpdatedAt"
        //             defaultMessage="Last scheduled time"
        //         />
        //     ),
        //     sorter: true,
        //     dataIndex: 'updatedAt',
        //     valueType: 'dateTime',
        //     renderFormItem: (item, { defaultRender, ...rest }, form) => {
        //         const status = form.getFieldValue('status');
        //         if (`${status}` === '0') {
        //             return false;
        //         }
        //         if (`${status}` === '3') {
        //             return (
        //                 <Input
        //                     {...rest}
        //                     placeholder={intl.formatMessage({
        //                         id: 'pages.searchTable.exception',
        //                         defaultMessage: 'Please enter the reason for the exception!',
        //                     })}
        //                 />
        //             );
        //         }
        //         return defaultRender(item);
        //     },
        // },
        {
            title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
            dataIndex: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    key="config"
                    onClick={() => {
                        handleUpdateModalOpen(true);
                        setCurrentRow(record);
                    }}
                >
                    更改端口配置
                </a>
            ],
        },
    ];

    const sendMessage = function () {

    }
    const closeAdd = function () {
        setOpenAddPort(false)
    }
    return (
        <PageContainer>
            {/* 整个table */}
            <ProTable<API.RuleListItem, API.PageParams>
                //分页
                //首页标题栏

                headerTitle={'端口展示'}
                actionRef={actionRef}//为useref 得到现在操作的dom元素
                rowKey="key"
                search={false}
                // search={{
                //     labelWidth: 120,
                // }}//搜索栏label宽度
                pagination={{
                    pageSize: gridData ? gridData.pageSize : 10,
                    total: gridData ? gridData.total : 0,
                    current: gridData ? gridData.pageIndex : 1,
                    showSizeChanger: true,
                    onChange: paginationChange
                }}
                // 工具栏
                toolBarRender={() => [
                    //+新增按钮
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalOpen(true);//通过改变bool state打开新建规则弹窗
                            setOpenAddPort(true)
                            console.log('打开新建', createModalOpen)
                        }}
                    >
                        <PlusOutlined />
                        {/* +新建 */}
                        新建端口
                    </Button>,
                ]}
                //请求的网络接口
                request={rule}//网络接口
                columns={columns}//每行
                rowSelection={{//选择哪一行的控制
                    onChange: (rowDetail, selectedRows) => {
                        console.log(selectedRows, rowDetail)//两者皆为数组
                        setSelectedRows(selectedRows);//setSelect为state
                    },
                }}
            />

            {/* 开始选择后出现的 */}
            {selectedRowsState?.length > 0 && (
                // 底部栏
                <FooterToolbar
                    extra={
                        <div>
                            <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
                            <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
                            <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
                        </div>
                    }
                >
                    <Button type="primary" danger
                        onClick={async () => {
                            //网络传输删除
                            await handleRemove(selectedRowsState);
                            // 设置选择的行为空
                            setSelectedRows([]);
                            // 当前的dom元素
                            actionRef.current?.reloadAndRest?.();//刷新表格重置页码 但不会清空表单
                        }}
                    >
                        <FormattedMessage
                            id="pages.searchTable.batchDeletion"
                            defaultMessage="Batch deletion"
                        />
                    </Button>
                </FooterToolbar>
            )}
            {/* 终止-开始选择 */}

            {/* 点击新建规则后，弹出的新建规则框 */}
            {/* <ModalForm
                title={intl.formatMessage({
                    id: 'pages.searchTable.createForm.newRule',
                    defaultMessage: 'New rule',
                })}
                width="1600px"
                open={createModalOpen}//通过这个bool值打开新建规则 来自于点击按钮
                onOpenChange={handleModalOpen} //通过这个自己开关弹窗
                onFinish={async (value) => { //点击保存后进行网络请求
                    console.log(value)
                    setOpenAddPort(true)//通知子组件要传输
                    // setOpenAddPort(true)
                    const success = await handleAdd(value as API.RuleListItem);
                    setOpenAddPort(false)
                    if (success) {
                        handleModalOpen(false); //开关弹窗
                        if (actionRef.current) { //？？
                            actionRef.current.reload();
                        }
                    }
                }}
            >
            </ModalForm> */}
            {/* 新建端口弹窗 */}
            {openAddPort == true ? (<AddPort CloseAdd={closeAdd}></AddPort>) : null}

            {/* 终止-新建规则 */}

            {/* 更新列表 */}
            {/* 侧边栏打开看详细信息*/}
            <Drawer
                width={600}
                open={showDetail}// 控制打开的state
                onClose={() => {
                    setCurrentRow(undefined);//关闭后当前行为空
                    setShowDetail(false);//关闭
                }}
                closable={false}
            >
                {currentRow?.name && (//当前行的信息展示
                    <ProDescriptions<API.RuleListItem>
                        column={2}
                        title={currentRow?.name}
                        request={async () => ({
                            data: currentRow || {},
                        })
                        }
                        params={{
                            id: currentRow?.name,
                        }}
                        columns={columns as ProDescriptionsItemProps<API.RuleListItem>[]}
                    />
                    //具体信息
                )}
            </Drawer>
            {/* 终止-更改紧密程度 */}
        </PageContainer>
    );
};

export default TableList;
